package io.renren.common.utils;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;

public class MailUtils  {
    private static final Logger logger = LoggerFactory.getLogger(MailUtils.class);

    static String HOST = "";//smtp服务器
    static String FROM = "";//发件人地址
    static String USER = "";//用户名
    static String PWD = "";//授权码
    static String SUBJECT = "";//邮件标题

    static {
        Properties properties = new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("mail.properties"));
            HOST = properties.getProperty("mail.HOST");
            FROM = properties.getProperty("mail.FROM");
            USER = properties.getProperty("mail.USER");
            PWD = properties.getProperty("mail.PWD");
            SUBJECT = properties.getProperty("mail.SUBJECT");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static R sendMail(String to, String code) {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", HOST);//设置服务器属性
        properties.put("mail.smtp.auth", "true");//授权
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, PWD);
            }
        });

        try {
            //创建对象
            MimeMessage message = new MimeMessage(session);
            //set FROM:头部字段
            message.setFrom(new InternetAddress(FROM));
            //set TO:头部字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //主题
            message.setSubject(SUBJECT);
            //邮件内容
            message.setText("验证码是：" + code + "。无需回复此邮件！！！");
            //发送邮件
            Transport.send(message);

            logger.info("发送成功！！");
            return R.ok("发送成功");
        } catch (AddressException e) {
            e.printStackTrace();
            return R.error("发送失败");
        } catch (MessagingException e) {
            e.printStackTrace();
            return R.error("发送失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("发送失败");
        }
    }

}
